import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_common/flutter_common.dart';
import 'package:flutter_common/util/context_extension.dart';

const double _HEIGHT = 44;
class FxAppBar extends StatefulWidget implements PreferredSizeWidget {

  final String title;
  ///是否显示返回按钮
  final bool showBack;
  ///标题居中显示，默认居左
  final bool center;
  ///左边的按钮，用于替代返回键
  Widget? leftWidget;
  VoidCallback? onBackPressed;
  final VoidCallback? onTitlePressed;
  final List<Widget>? actions;
  final SystemUiOverlayStyle? style;
  final EdgeInsetsGeometry? padding;
  final Color? themeColor;
  final Color? backgroundColor;
  FxAppBar({Key? key, required this.title,this.onBackPressed, this.leftWidget, this.showBack = true,  this.center = false, this.onTitlePressed, this.actions, this.style, this.padding, this.themeColor, this.backgroundColor}) : super(key: key);

  @override
  State<FxAppBar> createState() => _FxAppBarState();

  @override
  Size get preferredSize => const Size.fromHeight(_HEIGHT);
}

class _FxAppBarState extends State<FxAppBar> {

  final GlobalKey _actionKey = GlobalKey();
  double _actionWidth = 60;

  @override
  Widget build(BuildContext context) {
    _getRowWidth();
    MediaQueryData data = MediaQuery.of(context);
    double statusBarHeight = data.padding.top;
    EdgeInsetsGeometry p = EdgeInsets.only(top: statusBarHeight);
    if(widget.padding != null) p.add(widget.padding!);
    Widget w = Ink(
        color: widget.backgroundColor??FxTheme().appBarBgColor,
        height: _HEIGHT + statusBarHeight,
        width: data.size.width,
        padding: p,
        child: _appBar(context));
    if (widget.style != null) {
      w = AnnotatedRegion<SystemUiOverlayStyle>(value: widget.style!, child: w);
    }
    return w;
  }

  _appBar(BuildContext context) {
    return Stack(
      alignment: Alignment.centerLeft,
      children: [
        _title(),
        if (widget.leftWidget != null) widget.leftWidget! else if (widget.showBack) _back(context),
        if (widget.actions != null && widget.actions!.isNotEmpty)
          Positioned(key: _actionKey, right: 0, child: Row(children: widget.actions!)),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    _getRowWidth();
  }

  void _getRowWidth() {
    // 确保在框架构建完成后执行
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final RenderBox? renderBox = _actionKey.currentContext?.findRenderObject() as RenderBox?;
      if (renderBox != null) {
        final double width = renderBox.size.width;
        if(width > _actionWidth) {
          _actionWidth = width;
          setState(() {});
        }
      }
    });
  }

  _back(BuildContext context) => InkWell(
      onTap: widget.onBackPressed ?? () => context.pop(),
      child: SizedBox(
          width: _HEIGHT,
          height: _HEIGHT,
          child: Icon(
            Icons.arrow_back_ios,
            color: widget.themeColor?? const Color(0xff000033),
            size: 17,
          )));

  _title() {
    String newTitle = widget.title;
    // if(title.length > 20) {
    //   newTitle = title;//.substring(0, 20) + '...';
    // }
    Widget t = Text(newTitle,
        softWrap: false,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
            color: widget.themeColor ?? const Color(0xff000033),
            overflow: TextOverflow.ellipsis,
            fontWeight: lightBold,
            fontSize: fontSize32));
    if (widget.onTitlePressed != null) {
      t = InkWell(onTap: widget.onTitlePressed, child: t);
    }
    t = Align(
        alignment: widget.center ? Alignment.center : Alignment.centerLeft,
        child: t);
    if (widget.center) {
      return Padding(
          padding: EdgeInsets.symmetric(horizontal: _actionWidth), child: t);
    } else {
      return Padding(
          padding: EdgeInsets.only(left: widget.showBack ? 44 : 15,right: widget.actions != null ? _actionWidth : 15), child: t);
    }
  }
}

class FxAppBarStateless extends StatelessWidget implements PreferredSizeWidget {

  static const double _HEIGHT = 44;
  final String title;
  ///是否显示返回按钮
  final bool showBack;
  ///标题居中显示，默认居左
  final bool center;
  ///左边的按钮，用于替代返回键
  Widget? leftWidget;
  VoidCallback? onBackPressed;
  final VoidCallback? onTitlePressed;
  final List<Widget>? actions;
  final SystemUiOverlayStyle? style;
  final EdgeInsetsGeometry? padding;
  final Color? themeColor;
  final Color? backgroundColor;

  final GlobalKey _actionKey = GlobalKey();
  double _actionWidth = 60;

  FxAppBarStateless(
      {Key? key,
        required this.title,
        this.onBackPressed,
        this.leftWidget,
        this.center = false,
        this.onTitlePressed,
        this.padding,
        this.actions,
        this.backgroundColor,
        this.showBack = true, this.style, this.themeColor})
      : super(key: key);



  @override
  Widget build(BuildContext context) {
    _getRowWidth();
    MediaQueryData data = MediaQuery.of(context);
    double statusBarHeight = data.padding.top;
    EdgeInsetsGeometry p = EdgeInsets.only(top: statusBarHeight);
    if(padding != null) p.add(padding!);
    Widget w = Ink(
        color: backgroundColor??FxTheme().appBarBgColor,
        height: _HEIGHT + statusBarHeight,
        width: data.size.width,
        padding: p,
        child: _appBar(context));
    if (style != null) {
      w = AnnotatedRegion<SystemUiOverlayStyle>(value: style!, child: w);
    }
    return w;
  }

  _appBar(BuildContext context) {
    return Stack(
      alignment: Alignment.centerLeft,
      children: [
        _title(),
        if (leftWidget != null) leftWidget! else if (showBack) _back(context),
        if (actions != null && actions!.isNotEmpty)
          Positioned(key: _actionKey, right: 0, child: Row(children: actions!)),
      ],
    );
  }

  void initState() {
    _getRowWidth();
  }

  void _getRowWidth() {
    // 确保在框架构建完成后执行
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final RenderBox? renderBox = _actionKey.currentContext?.findRenderObject() as RenderBox?;
      if (renderBox != null) {
        final double width = renderBox.size.width;
        if(width > _actionWidth) {
          _actionWidth = width;

        }
        print("Row width: $width");  // 你可以在这里使用这个宽度
      }
    });
  }

  _back(BuildContext context) => InkWell(
      onTap: onBackPressed ?? () => context.pop(),
      child: SizedBox(
          width: _HEIGHT,
          height: _HEIGHT,
          child: Icon(
            Icons.arrow_back_ios,
            color: themeColor?? const Color(0xff000033),
            size: 15,
          )));

  _title() {
    String newTitle = title;
    // if(title.length > 20) {
    //   newTitle = title;//.substring(0, 20) + '...';
    // }
    Widget t = Text(newTitle,
        softWrap: false,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
            color: themeColor ?? const Color(0xff000033),
            overflow: TextOverflow.ellipsis,
            fontWeight: lightBold,
            fontSize: fontSize32));
    if (onTitlePressed != null) {
      t = InkWell(onTap: onTitlePressed, child: t);
    }
    t = Align(
        alignment: center ? Alignment.center : Alignment.centerLeft,
        child: t);
    if (center) {
      return t;
    } else {
      return Padding(
          padding: EdgeInsets.only(left: showBack ? 44 : 15,right: actions != null ? _actionWidth : 15), child: t);
    }
  }

  @override
  Size get preferredSize => const Size.fromHeight(_HEIGHT);
}

///自带一个 appbar
class FxScaffold extends Scaffold {
  FxScaffold({
    Key? key,
    String? title,
    PreferredSizeWidget? appBar,
    bool? resizeToAvoidBottomInset,
    VoidCallback? onBackPressed,
    Color? backgroundColor,
    required Widget body,
  }) : super(
      key: key,
      backgroundColor: backgroundColor,
      resizeToAvoidBottomInset: resizeToAvoidBottomInset,
      appBar: _copyAppBar(title, appBar, onBackPressed),
      body: onBackPressed == null
          ? body
          : WillPopScope(
          child: body,
          onWillPop: () async {
            onBackPressed();
            return false;
          }));

  ///标题居中
  FxScaffold.Center(
      {Key? key, required String title,
        VoidCallback? onBackPressed,
        Color? backgroundColor,
        required Widget body})
      : this(
      key: key,
      body: body,
      backgroundColor: backgroundColor,
      appBar: FxAppBar(
          title: title, center: true, onBackPressed: onBackPressed));
}

_copyAppBar(String? title,PreferredSizeWidget? appBar, VoidCallback? onBackPressed) {
  if(appBar == null) return FxAppBar(title: title ?? '', onBackPressed: onBackPressed);
  if(appBar is FxAppBar && appBar.onBackPressed == null && onBackPressed != null) {
    appBar.onBackPressed = onBackPressed; ///复用返回键的回调，免得有些appbar的返回键忘了写
  }
  return appBar;
}